function isType(val, type) {
  val = Object.prototype.toString.call(val).toLowerCase();
  if (typeof type === "string") {
    return val === "[object " + type.toLowerCase() + "]";
  }
  return val.replace(/(\[object\s)|(\])/g, "");
}

function isParse(value) {
  let data;
  try {
    data = JSON.parse(value);
  } catch (error) {
    data = value;
    console.log("试图转换JSON.parse函数不支持的数据字符串 =>", value);
  }
  return data;
}

function isStringify(value) {
  if (
    (isType(value) === "string" && value.search(/[^\.0-9]/g) >= 0) ||
    isType(value) === "string" ||
    isType(value) === "function" ||
    value === undefined ||
    value === "undefined" ||
    value === "NaN" ||
    (typeof value === "number" && String(value) == "NaN")
  ) {
    return value;
  } else {
    return JSON.stringify(value);
  }
}

let Storage = function(db) {
  return {
    key(index) {
      let data = db.key(index);
      return isParse(data);
    },
    get(key) {
      let data = db.getItem(key);
      return isParse(data);
    },
    set(key, value) {
      let data = isStringify(value);
      db.setItem(key, data);
      return value;
    },
    remove(key) {
      let data = this.get(key);
      db.removeItem(key);
      return data;
    },
    clear() {
      db.clear();
    }
  };
};

export let LDB = Storage(localStorage);
export let SDB = Storage(sessionStorage);